<?php
declare (strict_types=1);

namespace app\admin\logic\finance;

use app\admin\logic\system\Log;
use app\admin\model\finance\CreditConfig as CreditConfigModel;
use app\common\exception\LogicException;
use Exception;

/**
 * 积分配置
 */
class CreditConfig extends CreditConfigModel
{
    /**
     * 获取配置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-23
     *
     */
    public static function getScore(string $key, $default = [])
    {
        $config = app(CreditConfigModel::class)->where('key', $key)->where('mhm_id', request()->mhm_id)->findOrEmpty();

        return !$config->isEmpty() ? $config->getAttr('score') : $default;
    }

    /**
     * 批量设置
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-23
     *
     * @throws Exception
     */
    public function batchSetting(array $data = [])
    {
        $save = array_map(function ($key, $score) {
            return ['mhm_id' => request()->mhm_id, 'key' => $key, 'score' => $score];
        }, array_keys($data), $data);

        $res = $this->replace()->saveAll($save);
        if ($res->isEmpty()) throw new LogicException('保存失败');

        Log::write('更新积分配置', 'credit', 'update', true);
    }
}
